package cn.finder.httpcommons.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


public class WebUtils {
	
	
	 private int timeout = 6000;
	 

     public String buildGetUrl(String url, Map<String, String> parameters)
     {
         if ((parameters != null) && (parameters.size() > 0))
         {
             if (url.contains("?"))
             {
                 url = url + "&" + buildQuery(parameters);
                 return url;
             }
             url = url + "?" + buildQuery(parameters);
         }
         return url;
     }
     
     public static String buildQuery(Map<String, String> parameters)
     {
         StringBuffer builder = new StringBuffer();
         
         boolean flag = false;
         
         Set<Entry<String, String>> setEntrys = parameters.entrySet();
         
         Iterator<Entry<String, String>> itr = setEntrys.iterator();
         
         
         while (itr.hasNext())
         {
             
             Entry<String,String> current = itr.next();
             
             String key = current.getKey();
             String value = current.getValue();

             if (!CommonUtils.isEmpty(key))
             {
                 if (flag)
                 {
                     builder.append("&");
                 }
                 builder.append(key);
                 builder.append("=");

                 
                 try {
					builder.append(URLEncoder.encode(value, "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
                 flag = true;
             }
         }
         return builder.toString();
         
         
     }

   /*    public boolean checkValidationResult(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
     {
         return true;
     }*/

     public String doGet(String url, Map<String, String> parameters)
     {
         if ((parameters != null) && (parameters.size() > 0))
         {
             if (url.contains("?"))
             {
                 url = url + "&" + buildQuery(parameters);
             }
             else
             {
                 url = url + "?" + buildQuery(parameters);
             }
         }
         String retStr ="";
         try {
        	 retStr = doGet(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
         return retStr;
         
     }

     
     public String doGet(String url)
     {
    	 String returnStr="{}";
       

    	try {
    		 // 创建默认的httpClient实例.    
    		HttpClient httpclient=null;
    		if(url.toLowerCase().startsWith("https")){
    			httpclient=createSSLClientDefault();
    		}else{
    			httpclient=new  DefaultHttpClient();
    		}
    		
            // 创建httppost    
            HttpGet http = new HttpGet(url);
            
            UrlEncodedFormEntity uefEntity;  
            try {  
                
                HttpResponse response = httpclient.execute(http);  
                try {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                    	returnStr=EntityUtils.toString(entity, "UTF-8");
                    	
                    }  
                } finally {  
                   // response.close();
                }  
            } catch (Exception e) {  
            
            	e.printStackTrace();
            } finally {  
                // 关闭连接,释放资源    
                try {  
                   // httpclient.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
    		
		} catch (Exception e) {
			e.printStackTrace();
		}

    	 return returnStr;

     }
     
     
     public String doPost(String url, Map<String, String> parameters)
     {
    	return  doPost(url, parameters,null);
     }


     /// <summary>
     /// 发送Post请求 支持文件 文本 JEE和安卓  未进行验证, 目前不支持文件
     /// </summary>
     /// <param name="url"></param>
     /// <param name="textParams"></param>
     /// <param name="fileParams"></param>
     /// <returns></returns>
     
     @Deprecated
     public String doPostMultiPlatform(String url, Map<String, String> textParams, Map<String, FileItem> fileParams)
     {
    	 String returnStr="{}";

    	try {
    		
    		
    		
    		
    		
    		
    		
    		
    		 // 创建默认的httpClient实例.    
    		
    		HttpClient httpclient=new  DefaultHttpClient();
    		
    		
    		
    	/*	HttpGet get =new HttpGet(url);
    	    HttpResponse res =	httpclient.execute(get);
    	    HttpEntity entity1 = res.getEntity();  
            if (entity1 != null) {  
            	returnStr=EntityUtils.toString(entity1, "UTF-8");
            	
            }  */
            
            
    		
            // 创建httppost    
            HttpPost httppost = new HttpPost(url);
            
         // 创建参数队列    
            List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 
            
            if(textParams!=null && textParams.size()>0){
            	Set<Entry<String, String>> entrySets= textParams.entrySet();
            	Iterator<Entry<String, String>> itr = entrySets.iterator();
            	
            	while(itr.hasNext()){
            		Entry<String,String> entry = itr.next();
                    BasicNameValuePair vp=new BasicNameValuePair(entry.getKey(), entry.getValue());
            		formparams.add(vp);
            	}
            	
            }
            UrlEncodedFormEntity uefEntity;  
            try {  
                uefEntity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);  
                httppost.setEntity(uefEntity);  
                
                HttpResponse response = httpclient.execute(httppost);  
                try {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                    	returnStr=EntityUtils.toString(entity, HTTP.UTF_8);
                    	
                    }  
                } finally {  
                   // response.close();
                }  
            } catch (Exception e) {  
            
            	e.printStackTrace();
            } finally {  
                // 关闭连接,释放资源    
                try {  
                   // httpclient.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
    		
		} catch (Exception e) {
			e.printStackTrace();
		}

    	 return returnStr;

     }
     
     
     /// <summary>
     /// 发送Post请求 如果在 ANDROID API 25以上的  由于已经移除了 HttpClient 会报 MultipartEntity NoClassDefFoundException
     /// </summary>
     /// <param name="url"></param>
     /// <param name="textParams"></param>
     /// <param name="fileParams"></param>
     /// <returns></returns>
     public String doPostMultipart(String url, Map<String, String> textParams, Map<String, FileItem> fileParams)
     {
    	 String returnStr="{}";
    	
       
    	 // 创建默认的httpClient实例.    
 		HttpClient httpclient=new  DefaultHttpClient();
    	try {
    		
    		
            // 创建httppost    
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-Type"," text/plain; charset=UTF-8");
            MultipartEntity reqEntity = new MultipartEntity();
         
            //文件
            if(fileParams!=null && fileParams.size()>0){
            	 //转换文件
	       		
	       		 
	       		 Set<Entry<String,FileItem>> setEntry = fileParams.entrySet();
	       		 
	       		 Iterator<Entry<String,FileItem>> itr =  setEntry.iterator();
	       		 int fileCnt=0;
	       		 while(itr.hasNext()){
	       			 fileCnt++;
	       			 Entry<String,FileItem> entry  = itr.next();
	       			 
	       			 String key = entry.getKey();
	       			 FileItem fileItem = entry.getValue();
	       			 
	       			// FileBody fileBody=new FileBody(fileItem.getFile(),key,fileItem.getMimeType(),HTTP.UTF_8);
	       			 
	       			 ByteArrayBody fileBody=new ByteArrayBody(fileItem.getContent(),fileItem.getMimeType(), key);
	       			 reqEntity.addPart(key, fileBody);
	       		 }
       		 
	       		
            	
            	
       	 	}
           
            if(textParams!=null && textParams.size()>0){
            	Set<Entry<String, String>> entrySets= textParams.entrySet();
            	Iterator<Entry<String, String>> itr = entrySets.iterator();
            	
            	while(itr.hasNext()){
            		Entry<String,String> entry = itr.next();
            		 String key = entry.getKey();
	       			 String  value = entry.getValue();
	       			 reqEntity.addPart(key, new StringBody(value,java.nio.charset.Charset.forName(HTTP.UTF_8)));
            	}
            }
            
            httppost.setEntity(reqEntity);
            
            HttpResponse response = httpclient.execute(httppost);  
            try {  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                	returnStr=EntityUtils.toString(entity, HTTP.UTF_8);
                }  
                
            } finally {  
               // response.close();
            }  
            
            
    		
		} catch (Exception e) {
			e.printStackTrace();
		}
    	finally{
    		httpclient.getConnectionManager().shutdown();
    	}
    	 return returnStr;

     }
     
     
     /// <summary>
     /// 发送Post请求 HTTP+SSL
     /// </summary>
     /// <param name="url"></param>
     /// <param name="textParams"></param>
     /// <param name="fileParams"></param>
     /// <returns></returns>
     public String doPostMultipartHttps(String url, Map<String, String> textParams, Map<String, FileItem> fileParams)
     {
    	 String returnStr="{}";
    	
       
    	 // 创建默认的httpClient实例.    
 		HttpClient httpclient=WebClientDevWrapper.wrapClient(new DefaultHttpClient());
    	try {
    		
 	        
            // 创建httppost    
            HttpPost httppost = new HttpPost(url);
          
            
            MultipartEntity reqEntity = new MultipartEntity();
            
            //List<FileBody> files=null;
            //文件
            if(fileParams!=null && fileParams.size()>0){
            	 //转换文件
            	//files=new ArrayList<FileBody>();
	       		
	       		 
	       		 Set<Entry<String,FileItem>> setEntry = fileParams.entrySet();
	       		 
	       		 Iterator<Entry<String,FileItem>> itr =  setEntry.iterator();
	       		 int fileCnt=0;
	       		 while(itr.hasNext()){
	       			 fileCnt++;
	       			 Entry<String,FileItem> entry  = itr.next();
	       			 
	       			 String key = entry.getKey();
	       			 FileItem fileItem = entry.getValue();
	       			 
	       			// FileBody fileBody=new FileBody(fileItem.getFile(),key,fileItem.getMimeType(),HTTP.UTF_8);
	       			 //files.add(fileBody);
	       			 ByteArrayBody fileBody=new ByteArrayBody(fileItem.getContent(),fileItem.getMimeType(), key);
	       			reqEntity.addPart(key, fileBody);
	       		 }
       		 
            	
            	
            	
       	 	}
            
            if(textParams!=null && textParams.size()>0){
            	Set<Entry<String, String>> entrySets= textParams.entrySet();
            	Iterator<Entry<String, String>> itr = entrySets.iterator();
            	
            	while(itr.hasNext()){
            		Entry<String,String> entry = itr.next();
            		 String key = entry.getKey();
	       			 String  value = entry.getValue();
	       			 reqEntity.addPart(key, new StringBody(value));
            	}
            }
            
            httppost.setEntity(reqEntity);
            
            HttpResponse response = httpclient.execute(httppost);  
            try {  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                	returnStr=EntityUtils.toString(entity, HTTP.UTF_8);
                }  
                
            } finally {  
               // response.close();
            }  
            
            
    		
		} catch (Exception e) {
			e.printStackTrace();
		}
    	finally{
    		httpclient.getConnectionManager().shutdown();
    	}
    	 return returnStr;

     }
     
     
     
   /// <summary>
     /// 发送Post请求
     /// </summary>
     /// <param name="url"></param>
     /// <param name="textParams"></param>
     /// <param name="fileParams"></param>
     /// <returns></returns>
     public String doPost(String url, Map<String, String> textParams, Map<String, FileItem> fileParams)
     {
    	 String returnStr="{}";
    	/* FormFile[] files=null;
    	 if(fileParams!=null && fileParams.size()>0){
    		 
    		 
    		 //转换文件
    		 files = new FormFile[fileParams.size()];
    		 
    		 Set<Entry<String,FileItem>> setEntry = fileParams.entrySet();
    		 
    		 Iterator<Entry<String,FileItem>> itr =  setEntry.iterator();
    		 int fileCnt=0;
    		 while(itr.hasNext()){
    			 fileCnt++;
    			 Entry<String,FileItem> entry  = itr.next();
    			 
    			 String key = entry.getKey();
    			 FileItem fileItem = entry.getValue();
    			 
    			 
    			 FormFile formFile=new FormFile(fileItem.getContent(), key, "myForm", fileItem.getMimeType());
    			 
    			 
    			 files[fileCnt-1]= formFile; 
    		 }
    		 
    		 
    	 }*/
       
    	 // 创建默认的httpClient实例.    
    	 HttpClient httpclient=null;
 		if(url.toLowerCase().startsWith("https")){
 			httpclient=createSSLClientDefault();
 		}else{
 			httpclient=new  DefaultHttpClient();
 		}
    	try {
    		
    		
    		
    		

            // 创建httppost    
            HttpPost httppost = new HttpPost(url);
    		
            httppost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    	
    		
           
            
         // 创建参数队列    
           List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 
            
            if(textParams!=null && textParams.size()>0){
            	Set<Entry<String, String>> entrySets= textParams.entrySet();
            	Iterator<Entry<String, String>> itr = entrySets.iterator();
            	
            	while(itr.hasNext()){
            		Entry<String,String> entry = itr.next();
                    BasicNameValuePair vp=new BasicNameValuePair(entry.getKey(), entry.getValue());
            		formparams.add(vp);
            	}
            	
            }
            UrlEncodedFormEntity uefEntity;  
            try {  
                uefEntity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);  
                httppost.setEntity(uefEntity);  
                
                HttpResponse response = httpclient.execute(httppost);  
                try {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                    	returnStr=EntityUtils.toString(entity, HTTP.UTF_8);
                    	
                    }  
                } finally {  
                   // response.close();
                }  
            } catch (Exception e) {  
            
            	e.printStackTrace();
            } finally {  
                // 关闭连接,释放资源    
                try {  
                   // httpclient.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            
            
            
            
            
    		
		} catch (Exception e) {
			e.printStackTrace();
		}
    	finally{
    		httpclient.getConnectionManager().shutdown();
    	}
    	 return returnStr;

     }
     /***
      * 
      * 直接发送POST数据 HTTP形式
      * @param url
      * @param data
      * @return
      */
     public String doPostData(String url, String data)
     {
    	 String returnStr="{}";
    	 String strData="";
		try {
			//strData = URLEncoder.encode(data, HTTP.UTF_8);
			strData=data;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    	 try {
    		 String CHARSET = "UTF-8";
             //创建连接
             URL theurl = new URL(url);
             HttpURLConnection connection = (HttpURLConnection) theurl.openConnection();
                     
             connection.setDoOutput(true);
             connection.setDoInput(true);
             connection.setRequestMethod("POST");
             connection.setUseCaches(false);
             connection.setInstanceFollowRedirects(true);
             connection.setRequestProperty("Content-Type",
                     "application/x-www-form-urlencoded");
             connection.setRequestProperty("Charset", CHARSET);

             connection.connect();

             //POST请求
             DataOutputStream out = new DataOutputStream(
                     connection.getOutputStream());

             out.write(strData.getBytes("utf-8"));
             out.flush();
             out.close();

             //读取响应
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                     connection.getInputStream(),"utf-8"));
             String lines;
             StringBuffer sb = new StringBuffer("");
             while ((lines = reader.readLine()) != null) {
                 //lines = new String(lines.getBytes(), "utf-8");
                 sb.append(lines);
                 sb.append("\n");//换行  需要加上  update by 20150928
             }
             //System.out.println(sb);
             returnStr = sb.toString();
             reader.close();
             // 断开连接
             connection.disconnect();
         } catch (MalformedURLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (UnsupportedEncodingException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }

    	 
    		
    	 return returnStr;
     }
     
     
     
     
     /***
      * 直接发送POST数据,获取textParams中第一个数据的值
      * @param url
      * @param textParams
      * @param fileParams
      * @return
      */
     @Deprecated
     public String doPostData(String url, Map<String, String> textParams, Map<String, FileItem> fileParams)
     {
    	
    	 String strData="";
    	 Set<Entry<String,String>> entrySet =textParams.entrySet();
    	 
    	 Iterator<Entry<String,String>> itr =entrySet.iterator();
    	 if(itr.hasNext()){
    		 Entry<String,String> entry= itr.next();
    		 strData=entry.getValue();
    	 }
    	 
    	 return doPostData(url, strData);
     }


      /***
       * 推荐 发送 HTTPS 请求  
       * @param url
       * @param method GET|POST
       * @param textParams 文本型参数
       * @param fileParams 文件型参数
       * @param useHttps 是否启用HTTPS ,默认为false
       * @return
       */
     public String doHttp(String url, String method,Map<String, String> textParams, Map<String, FileItem> fileParams,boolean useHttps){
    	 
    	 throw new RuntimeException("the method is not  implement");
    	 
    	 
    	 
     }
     
     /***
      * 发送请求 HTTPS  直接发送数据
      * @param url 请求地址
      * @param method GET|POST
      * @param data  要发送的数据 字符串
      * @return
      */
     public String doHttps(String url, String method,String data)
     {
    	 String returnStr="{}";
    	 String strData=data;
    	 try {
    		 
    		 SSLContext sc = SSLContext.getInstance("SSL");
    	        sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
    	                new java.security.SecureRandom());
    	        
             //创建连接
             URL theurl = new URL(url);
             
             HttpsURLConnection connection = (HttpsURLConnection) theurl.openConnection();
                     
             connection.setSSLSocketFactory(sc.getSocketFactory());
             connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
             connection.setDoOutput(true);
             connection.setDoInput(true);
             connection.setRequestMethod(method);//// 设置请求方式（GET/POST）
             connection.setUseCaches(false);
             connection.setInstanceFollowRedirects(true);
             connection.setRequestProperty("Content-Type",
                     "application/x-www-form-urlencoded");

             connection.connect();

             //POST请求
             DataOutputStream out = new DataOutputStream(
                     connection.getOutputStream());

             out.write(strData.getBytes("utf-8"));
             out.flush();
             out.close();

             //读取响应
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                     connection.getInputStream(),"utf-8"));
             String lines;
             StringBuffer sb = new StringBuffer("");
             while ((lines = reader.readLine()) != null) {
                // lines = new String(lines.getBytes(), "utf-8");
                 sb.append(lines);
             }
            // System.out.println("===请求返回数据:"+sb);
             returnStr = sb.toString();
             reader.close();
             // 断开连接
             connection.disconnect();
         } catch (ConnectException ce) {
        	 ce.printStackTrace();
         } catch (Exception e) {
             e.printStackTrace();
         }
    	 return returnStr;
     }
     
     
  // 如果是文本的文件的话那么通过map类传递进来如果是文件的话通过FormFile传递进来
 	/***
 	 * 既是上传又是下载 post请求
 	 * @param actionUrl  请求的地址  
 	 *   params 普通类型的参数
 	 *   files 二进制--流媒体或者文件, 图片等
 	 *   HttpURLConnection 只能上传小文件.因为文件缓存在内存中.所以内存溢出
 	 */
 	public  String post(String actionUrl, Map<String, String> params,String userName,String password,
 			FileItem[] files) throws IOException {

 		String BOUNDARY = "--------------et567z";
 		String MULTIPART_FROM_DATA = "Multipart/form-data";
 		String PREFIX="--",LINEND="\r\n";
 		String CHARSET = "UTF-8";
 		
 		URL uri = new URL(actionUrl);
 		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
 		//conn.setReadTimeout(5 * 1000); // 缓存的最长时间
 		conn.setDoInput(true);// 允许输入
 		conn.setDoOutput(true);// 允许输出
 		conn.setUseCaches(false); // POST不允许使用缓存
 		// 下面的几个值是必须需要设置进去的
 		conn.setRequestMethod("POST");
 		conn.setRequestProperty("Connection", "keep-alive");
 		conn.setRequestProperty("Charset", CHARSET);
 		conn.setRequestProperty("Accept", "application/json");
 		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
 				+ ";boundary=" + BOUNDARY);

 		//conn.setChunkedStreamingMode(1024*10);
 		
 		
 		
 		if(userName!=null)
 		{
 			String usernamePassword = userName + ":" + password;
 			conn.setRequestProperty("Authorization", "Basic "
 							+ new String(SecBase64.encode(usernamePassword
 									.getBytes())));
 		}
 		// 首先组拼文本类型的参数
 		StringBuilder sb = new StringBuilder();
 		sb.append(PREFIX + BOUNDARY + LINEND);//add by 2016-07-16
 		
 		
 		if(params!=null)
 		{
 			
 			// 这个地方使用了Map循环 map循环的方式需要注意一下了
 			for (Map.Entry<String, String> entry : params.entrySet()) {
 				sb.append(PREFIX);
 				sb.append(BOUNDARY);
 				// 回车换行
 				sb.append(LINEND);
 				sb.append("Content-Disposition:form-data;name=\"" + entry.getKey()
 						+ "\"" + LINEND);
 				sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND);
 			    sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
 				
 			    sb.append(LINEND);
 			    sb.append(URLEncoder.encode(entry.getValue()==null?"":entry.getValue(),CHARSET)); 
 			    //sb.append(entry.getValue());
 			    sb.append(LINEND);
 			}
 			
 		}
 		DataOutputStream outStream = new DataOutputStream(
 				conn.getOutputStream());
 		if(sb.length()>0)
 		{
 			outStream.write(sb.toString().getBytes(CHARSET));
 		}
 		// 前面必须是数组才可以
 		// 发送文件数据
 		if(files!=null && files.length>0)
 		{
 			for (FileItem file : files) {
 	
 				StringBuilder sb1 = new StringBuilder();
 				sb1.append(PREFIX);
 				sb1.append(BOUNDARY);
 				sb1.append(LINEND);
 				// 这个地方没有完  注意 这里的 filename name的设置的值 有可能变化
 				sb1.append("Content-Disposition:form-data;name=\""
 						+ file.getFileName()+"\"; filelength=\""+file.getContent().length+"\"; filename=\""+file.getFileName()+"\""+LINEND);
 				sb1.append("Content-Type: "+file.getMimeType()+"; charset="+CHARSET+LINEND);
 				

 				//sb1.append("Content-Type: "+"application/octet-stream"+"; charset="+CHARSET+LINEND);
 				
 				sb1.append(LINEND);
 				outStream.write(sb1.toString().getBytes(CHARSET));
 	
 				// 先判断formfile里面是否为空 如果不为空的话则写出 获取formfile的data里面的
 				
 				/*InputStream is=file.getInStream();
 				if (is != null) {
 					// 提供流的的方式的话就是一边读一边写了
 					byte[] buffer = new byte[1024*10];
 					int len = 0;
 					while ((len = is.read(buffer)) != -1) {
 						outStream.write(buffer, 0, len);
 					}
 					file.getInStream().close();
 				} else {
 					outStream.write(file.getContent(), 0, file.getContent().length);
 	
 				}*/
 				outStream.write(file.getContent(), 0, file.getContent().length);
 				outStream.write(LINEND.getBytes(CHARSET));
 	
 			}
 		}
 		byte[] end_data = (PREFIX + BOUNDARY +PREFIX+ LINEND).getBytes(CHARSET);
 		outStream.write(end_data);
 		outStream.flush();

 		// 得到响应号码
 		int res = conn.getResponseCode();
 		if (res != 200)
 			throw new RuntimeException("请求失败 ");
 		/*InputStream in = conn.getInputStream();
 		int ch;
 		StringBuilder sb2 = new StringBuilder();
 		while ((ch = in.read()) != -1) {
 			sb2.append((char) ch);
 		}*/
 		StringBuilder sb2 = new StringBuilder();
 		String line=null;
 		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//设置编码,否则
 		while ((line = reader.readLine()) != null){
 			//lines = new String(lines.getBytes(), "utf-8");
 			sb2.append(line);
 		}
 		reader.close();
 		conn.disconnect();
 		// return in == null ? null : in.toString();
 		return sb2.toString();
 	}
     
     
     
     
     
     /***
      * 
      * @param url
      * @param method
      * @param data
      * @return
      */
     public String doHttps(String url, String method,Map<String,String> textParams)
     {
    	 String strData=JsonUtils.getJsonString4JavaPOJO(textParams);
    	 return doHttps(url,method ,strData);
     }
     
	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
//--------------------------------------------------------------------------------
	private static class TrustAnyTrustManager implements X509TrustManager {
		 
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
 
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
 
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }
	
	 private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
     }
	
//-------------==============================================================
    
	 
	 
	 
	 
	 
	 
	 /**
	     * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
	     * 不用导入SSL证书
	     * @author shipengzhi(shipengzhi@sogou-inc.com)
	     *
	     */
	    public static class WebClientDevWrapper {

	        public static org.apache.http.client.HttpClient wrapClient(org.apache.http.client.HttpClient httpClient) {
	            try {
	                SSLContext ctx = SSLContext.getInstance("TLS");
	                
	                ctx.init(null, new TrustManager[] { new TrustAnyTrustManager() }, null);
	                org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(ctx,org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	                httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssf,443 ));
	                
	                return httpClient;
	            } catch (Exception ex) {
	                ex.printStackTrace();
	                return null;
	            }
	        }
	    }
	    
	    /***
	     * 带有证书的HTTPS + SSL 请求
	     * @author Administrator
	     *
	     */
	public static class ClientCertHttpsSSL {

		
		/***
		 * 发送 HTTPS+SSL请求
		 * @param url  
		 * @param method GET|POST
		 * @param data  一般JSON | XML的数据类型
		 * @param certFilePath  证书文件路径 -绝对路径
		 * @param certPwd    证书密码
		 * @return 请求返回结果
		 * @throws Exception
		 */
		public String doRequest(String url, String method, String data,String certFilePath,
				String certPwd) throws Exception {
			/*System.out.println("url="+url);
			System.out.println(method);
			System.out.println(data);
			System.out.println(certFilePath);
			System.out.println(certPwd);*/
			String retStr = "{}";

			CloseableHttpResponse response = null;
			CloseableHttpClient httpclient = null;

			try {

				KeyStore keyStore = KeyStore.getInstance("PKCS12");
				System.out.println("=====keyStore:"+keyStore);
				FileInputStream instream = new FileInputStream(new File(
						certFilePath));
				
				System.out.println("=====instream:"+instream);
				keyStore.load(instream, certPwd.toCharArray());
				instream.close();
				
				//System.out.println("=====keyStore.load end");

				// Trust own CA and all self-signed certs
				SSLContext sslcontext = SSLContexts.custom()
						.loadKeyMaterial(keyStore, certPwd.toCharArray())
						.build();
				// Allow TLSv1 protocol only
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
						sslcontext,
						new String[] { "TLSv1" },
						null,
						SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
				httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
						.build();

				HttpPost httpReq = null;

				if ("GET".equalsIgnoreCase(method)) {
					//httpReq = new HttpGet(url);
					
				} else {
					httpReq = new HttpPost(url);
				}
				httpReq.setEntity(new StringEntity(data, "UTF-8"));
				
				/*httpReq.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				httpReq.addHeader("Host", "api.mch.weixin.qq.com");
				httpReq.addHeader("X-Requested-With", "XMLHttpRequest");
				httpReq.addHeader("Cache-Control", "max-age=0");
				httpReq.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");*/
				
		       
				
				
				response = httpclient.execute(httpReq);
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					retStr = EntityUtils.toString(entity, HTTP.UTF_8);
					EntityUtils.consume(entity);
				}

			} catch (Exception e) {

			} finally {
				response.close();
				httpclient.close();
			}
			return retStr;
		}
	}
	
	
	
	/***
	 * 创建普通的 ssl client
	 * @return
	 */
	private static CloseableHttpClient createSSLClientDefault() {

        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] xcs, String string){
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException ex) {
        } catch (NoSuchAlgorithmException ex) {
        } catch (KeyManagementException ex) {
        }

        return HttpClients.createDefault();
    }
	    
}
